from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from sqlalchemy import text
from werkzeug.security import generate_password_hash

from app.models.models import Courses, Users
from app import db
users = Blueprint('users', __name__)

@users.route('/users')
def list_users():
    result = db.session.execute(text("""
                    SELECT 
                        users.id, 
                        users.username, 
                        users.role
                    FROM 
                        users
                    where users.role != 'admin'
                    ORDER BY 
                        users.id DESC
                    """))
    users = result.fetchall()
    return render_template('user/list.html', users=users)

@users.route('/user/new')
def new_user():
    return render_template('user/add_user.html')

@users.route('/user/add_user', methods=['POST', 'GET'])
def add_user():
    if request.method == 'POST':
        print('进来了')
        data = request.get_json()
        username = data.get('userName')
        password = data.get('userPassword')
        role = data.get('userRole')

        user = Users.query.filter_by(username=username).first()
        if user:
            flash('Username already exists.')
            return jsonify({'error': '用户名已存在'}), 400

        new_user = Users(username=username, password=generate_password_hash(password, method='pbkdf2:sha256'), role=role)
        db.session.add(new_user)
        db.session.commit()
        flash('Registration successful.')
        return jsonify({'message': '用户注册成功'}), 200

    return jsonify({'error': 'Invalid request method'}), 405
